from io import BytesIO
from django.http import HttpResponse
from django import forms
from accounts.utils.bootstrap import BootStrapForm
from accounts import models
from accounts.forms import LoginForm

from django.shortcuts import render, redirect
from django.contrib import messages
from accounts.utils.code import check_code



def register_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')
        confirm_password = request.POST.get('confirm_password')
        role = request.POST.get('register_role')

        if password != confirm_password:
            messages.error(request, '两次输入的密码不一致')
            return redirect('register')

        if models.CultureAdmin.objects.filter(username=username).exists() or \
                models.RegularUser.objects.filter(username=username).exists():
            return render(request, 'auth/register..html', {'error': '用户名已存在'})

        # 根据角色分配用户组
        if role == 'culture':
            models.CultureAdmin.objects.create(username=username, password=confirm_password, email=email)
            return redirect('register')
        elif role == 'admin':
            # 通常管理员账号不能直接注册，需要特殊授权
            messages.error(request, '管理员账号需要特殊授权')
            return redirect('register')
        else:
            # 默认普通用户
            models.RegularUser.objects.create(username=username, password=confirm_password, email=email)
            return render(request, "auth/login.html")

    return render(request, 'auth/login.html')


# def login(request):
#     if request.method == "GET":
#         form = LoginForm
#         return render(request, 'auth/login.html', {'form': form})
#     form = LoginForm(data=request.POST)
#     if form.is_valid():
#         # 获取表单中的用户对象（已在clean方法中验证过）
#         user = form.user
#
#         # 执行登录操作
#         auth_login(request, user)
#
#         # 获取角色选择
#         login_role = request.POST.get('login_role', 'user')
#
#         # 根据角色重定向到不同页面
#         if login_role == 'admin':
#             return redirect('admin_dashboard')
#         elif login_role == 'culture':
#             return redirect('culture_dashboard')
#         else:
#             return redirect('user_dashboard')
#
#     # 如果表单无效，重新渲染登录页面并显示错误
#     return render(request, 'auth/login.html', {'form': form})


# def image_code(request):
#     """生成图片验证码"""
#     img, code_str = check_code()
#
#     request.session['image_code'] = code_str
#     # 给session设置60秒超时
#     request.session.set_expiry(60)
#
#     stream = BytesIO()
#     img.save(stream, "png")
#
#     return HttpResponse(stream.getvalue())


class LoginForm(BootStrapForm):
    username = forms.CharField(
        label='用户名',
        widget=forms.TextInput,
        required=True
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(render_value=True),  # 输入后密码不消失
        required=True
    )
    # code = forms.CharField(
    #     label='验证码',
    #     widget=forms.TextInput,
    #     required=True
    # )


def login(request):
    if request.method == "GET":
        form = LoginForm()
        return render(request, 'auth/login.html', {'form': form})
    form = LoginForm(data=request.POST)
    if form.is_valid():

        # 为什么用pop 因为后续需要使用username和password到数据库进行校验，不能含有code
        # user_input_code = form.cleaned_data.pop('code')
        # code = request.session.get('image_code', '')
        # if user_input_code.upper() != code.upper():
        #     form.add_error('code', '验证码错误')
        #     return render(request, 'auth/login.html', {'form': form})

        # admin_obj = models.Admin.objects.filter(username="xxx",password=pwd).first()
        # **form.cleaned_data 中字典中的字段名和LoginForm中设置的字段名一致，所以应保持LoginForm中字段名和数据库中一致
        user_obj = models.RegularUser.objects.filter(**form.cleaned_data).first()
        if not user_obj:
            # password表示 错误显示到password下面
            form.add_error('password', '用户名或密码错误')
            return render(request, 'auth/login.html', {'form': form})

        # 用户名密码正确
        # 网站随机生成字符串；写到用户浏览器的cookie中；再写到session中
        request.session['info'] = {'id': user_obj.id, 'username': user_obj.username}
        # 重新设置超时时间 7天
        request.session.set_expiry(60 * 60 * 24 * 7)
        # return redirect('/homepage/')
        return render(request,'homepage.html')

    return render(request, 'auth/login.html', {'form': form})

def logout(request):
    request.session.clear()
    return redirect('/login/')
